package com.shuoyue.adven;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.sm.appbase.base.XLog;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;


/**
 * 公共工具类
 * Author: Forty'7 on 2017/8/25 17:47
 * Email：xiaowangboke@vip.qq.com
 */
public class CommonUtil {
    /**
     * 获取应用的版本信息
     **/
    public static PackageInfo getVersionInfo(Context context) {
        PackageInfo info = null;
        try {
            PackageManager manager = context.getPackageManager();
            info = manager.getPackageInfo(context.getPackageName(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }

    /**
     * 关闭软键盘
     *
     * @param context
     * @param activity
     */
    public static void changeKeybroad(Context context, AppCompatActivity activity) {
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (activity.getCurrentFocus() != null)
            inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 屏幕信息
     *
     * @param context
     * @return
     */
    public static Point getScreenSize(Context context) {

        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getRealMetrics(displayMetrics);
        final int width = displayMetrics.widthPixels;
        final int height = displayMetrics.heightPixels;
        return new Point(width, height);
    }

    /**
     * 获得屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }


    public static String toURLEncoded(String paramString) {
        if (paramString == null || paramString.equals("")) {
            XLog.d("XLog", "toURLEncoded error:" + paramString);
            return "";
        }
        try {
            String str = new String(paramString.getBytes(), "UTF-8");
            str = URLEncoder.encode(str, "UTF-8");
            return str;
        } catch (Exception localException) {
            XLog.d("XLog", "toURLEncoded error:" + paramString);
        }
        return "";
    }


    public static String toURLDecoded(String paramString) {
        if (paramString == null || paramString.equals("")) {
            XLog.d("XLog", "toURLDecoded error:" + paramString);
            return "";
        }
        try {
            String str = new String(paramString.getBytes(), "UTF-8");
            str = URLDecoder.decode(str, "UTF-8");
            return str;
        } catch (Exception localException) {
            XLog.d("XLog", "toURLDecoded error:" + paramString);
        }

        return "";
    }


    public static int packageCode(Context context) {
        PackageManager manager = context.getPackageManager();
        int code = 0;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            code = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return code;
    }

    //获取版本名
    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    //获取版本号
    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }

    //通过PackageInfo得到的想要启动的应用的包名
    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pInfo = null;

        try {
            //通过PackageManager可以得到PackageInfo
            PackageManager pManager = context.getPackageManager();
            pInfo = pManager.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pInfo;
    }

    /**
     * 获取保存路径
     *
     * @return
     */
    public static String getPath() {
        File appDir = new File(Environment.getExternalStorageDirectory(), "日志");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        return appDir.getPath();
    }

    public static String getDownloadPath( ) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "apk");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        return appDir.getPath();
    }

    public static File getPathHdmi() {
        File appDir = new File(Environment.getExternalStorageDirectory().getPath() + "/hdmi");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        return appDir;
    }

    public static File getPathVideoCatch() {
        File appDir = new File(Environment.getExternalStorageDirectory().getPath() + "/adv_catch");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        return appDir;
    }

    public static File getPathLvds() {
        File appDir = new File(Environment.getExternalStorageDirectory().getPath() + "/lvds");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        return appDir;
    }

    /**
     * 保存图片
     */
    public static void saveBitmap(Bitmap bm) {
        File f = new File(Environment.getExternalStorageDirectory(), "板子文日志.png");
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 消息数量展示格式转换
     *
     * @return
     */
    public static String msgCountFormat(int count) {
        String strCount = "";
        if (count > 0) {
            strCount = "" + count;
            if (count > 99) strCount = "99+";
        }
        return strCount;
    }


    /**
     * 消息数量展示格式转换 并且 是否显示
     *
     * @return
     */
    public static String setMsgCountIsShow(View view, int count) {
        String strCount = "";
        if (count > 0) {
            strCount = "" + count;
            if (count > 99) strCount = "99+";
            view.setVisibility(View.VISIBLE);
        } else {
            view.setVisibility(View.INVISIBLE);
        }
        return strCount;
    }


    /**
     * 根据手机分辨率从DP转成PX
     *
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static String nullStrHandle(String string) {
        return string == null ? "" : string;
    }


    /**
     * 无需权限 获取手机唯一标识
     * Psuedo ID
     */
    public static String getUniquePsuedoID() {
        String serial = null;
        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +
                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +
                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +
                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +
                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +
                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +
                Build.USER.length() % 10; //13 位
        try {
            serial = Build.class.getField("SERIAL").get(null).toString();
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            //serial需要一个初始化
            serial = "serial"; // 随便一个初始化
        }
        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }


    @SuppressLint("MissingPermission")
    public static String getPhoneIMEI(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
        return tm.getDeviceId();
    }


    /**
     * 字符串空处理
     *
     * @return
     */
    public static String stringEmpty(String str) {
        if (TextUtils.isEmpty(str)) {
            return "";
        } else {
            return str;
        }
    }


    /**
     * 手机号格式处理（隐藏展示）
     *
     * @return
     */
    public static String phoneHide(String phone) {
        if (!TextUtils.isEmpty(phone)) {
            if (phone.length() >= 11) {
                phone = phone.substring(0, 3) + "****" + phone.substring(7, 11);
                return phone;
            } else {
                return phone;
            }
        } else {
            return "";
        }
    }

    /**
     * 获取APP版本号
     *
     * @param context
     * @return
     */
    public static int versionCode(Context context) {
        PackageManager manager = context.getPackageManager();
        int code = 0;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            code = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return code;
    }


    /**
     * 获取APP版本名
     *
     * @param context
     * @return
     */
    public static String versionName(Context context) {
        PackageManager manager = context.getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }

    /**
     * 判断版本更新
     *
     * @param version    本地app 版本号
     * @param minVersion 最新版本号
     * @return true 需要更新 false 不用
     */
    public static boolean minVersion(@NonNull String version, String minVersion) {

        List<String> versionNums = new ArrayList<>(Arrays.asList(version.split("\\.")));
        List<String> minVersionNums = new ArrayList<>(Arrays.asList(minVersion.split("\\.")));

        int len = Math.max(versionNums.size(), minVersionNums.size());
        for (int i = 0; i < len; i++) {
            if (versionNums.size() < i + 1) {
                versionNums.add("0");
            }

            if (minVersionNums.size() < i + 1) {
                minVersionNums.add("0");
            }

            int gap = Integer.valueOf(versionNums.get(i)) - Integer.valueOf(minVersionNums.get(i));
            if (gap != 0) {
                return gap < 0;
            }
        }

        return true;
    }


    /**
     * 保留小数点后两位小数
     *
     * @param value
     * @return
     */
    public static String decimal(double value) {
        return String.format("%.2f", value);
    }

    /**
     * 保留小数点后4位小数
     *
     * @param value
     * @return
     */
    public static String decimal4(double value) {
        return String.format("%.4f", value);
    }


    /**
     * 平仓类型
     */
    public static String getLiquidate(int type) {
        switch (type) {
            case 1:
                return "系统退定";
            case 2:
                return "客户退定";
            case 3:
                return "盈利退定";
            case 4:
                return "亏损退定";
            case 5:
                return "结算退定";
            case 6:
                return "获取实物退定";

            default:
                return "";
        }
    }

    /**
     * 切割String最后一位
     */
    public static String cutStringTail(String str) {
        if (!TextUtils.isEmpty(str)) {
            str = str.substring(0, str.length() - 1);
            return str;
        } else {
            return str;
        }
    }

    /**
     * 换行格式转换
     * return String = 活\n动
     */
    public static String lineFeedFormat(String tag) {
        if (!TextUtils.isEmpty(tag)) {
            String str = "";
            for (int i = 0, len = tag.length(); i < len; i++) {
                str += tag.substring(i, i + 1) + "\n";
            }
            tag = str;
            return tag;
        } else {
            return "";
        }
    }


    /**
     * @string 把list转换为一个用逗号分隔的字符串
     */
    public static String listToString(List<String> list, String split) {
        if (list.size() == 0) {
            return "";
        } else {
            StringBuilder sb = new StringBuilder();
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    if (i < list.size() - 1) {
                        sb.append(list.get(i) + split);
                    } else {
                        sb.append(list.get(i));
                    }
                }
            }
            return sb.toString();
        }
    }

    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }

    public static boolean isEquals1(String value) {
        if (value != null && value.equals("1")) {
            return true;
        }
        return false;
    }

    /**
     * @param context
     * @param fileName
     * @return
     */
    public static String getStringStrAssets(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assets = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assets.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}
